package com.woniu.shop.controller;

import com.woniu.entity.Result;
import com.woniu.entity.ResultCode;
import com.woniu.shop.constant.RedisConstant;
import com.woniu.shop.utils.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * 门店申请上传营业执照
 * @author LiFangyu
 * @since 2023/2/16 15:08
 */
@RestController
@RequestMapping("/upload")
@Api(tags = "阿里云对象存储控制类")
public class UploadController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/picture")
    @ApiOperation("上传图片")
    public Result<Object> uploadPic(@RequestPart MultipartFile file){
        if(file != null){
            String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = sdf.format(new Date()) + suffix;
            try {
                // 上传
                UploadUtil.upload(file, fileName);
                // 将上传内容记录到redis
                stringRedisTemplate.opsForSet().add(RedisConstant.ALIOSS_ALL_UPLOAD.name(), fileName);
                return Result.ok("上传成功");
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error(ResultCode.ERROR.getCode(), "上传失败");
            }
        }
        return Result.error(ResultCode.ERROR.getCode(), "获取不到图片");

    }

}
